package com.share.lagou.pipeline;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * inboundHandler
 * @author caifan
 * @since 2022/7/18
 */
public class SampleInBoundHandler extends ChannelInboundHandlerAdapter {

    private final String name;

    private final boolean flush;

    public SampleInBoundHandler(String name, boolean flush) {
        this.name = name;
        this.flush = flush;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("InBoundHandler:" + name);
        if (flush) {
            ctx.channel().writeAndFlush(msg);
        } else {
//            super.channelRead(ctx, msg);
            throw new RuntimeException("InBoundHandler:" + name);
        }
    }

    /**
     * 异常处理，ChannelHandler处理完再抛异常
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("InBoundHandlerException:" + name);
        ctx.fireExceptionCaught(cause);
    }
}
